<?php


namespace app\api\controller\v1;


use app\api\controller\v1\Clue as ClueModel;
use app\common\model\ClueErrorLog;
use app\lib\exception\ParamException;
use think\Db;

/**
 * 黑龙江惠客
 * 账户：16621777111
 *
 * 接入文档 - 金钱袋
 *  错误代码    说明
 *  0    请求正常响应（入库）
 *  200    撞库响应， 客户不存在（撞库）
 *  201    撞库响应， 客户已存在（入库、撞库）
 *  400    缺少参数，详情查看 msg 或 errors 返回值提示（入库、撞库）
 *  401    授权信息错误，请检查头部 X-Request-Channel 参数信息（入库、撞库）
 *  500    系统错误（入库、撞库）
 *  20010    手机号码格式错误（入库、撞库）
 * /
 */
class HeiLongJiangHuiKe2
{

    private $url='https://ti.hmgrun.com';
    private $app_id='knPI9y8ZrFAmnJVC';
    private $aeskey='StzSDom7N9uhyaUJ7kPlyzzcZUvd5GRy';
    private $aesiv='ZiG9qDXTgB8xzGb0';


    public function pushClue($mapping,$clue_info,$listPush)
    {

        $apiName='【'.$mapping['api_name'].'】';

//        $clue_info['clue_name']='测试';
//        $clue_info['phone']='15988888881';

        $clue_rule = json_decode($mapping['rule_json'], true);
        $params = [];
        if(!$clue_rule){
            $errMsg=$apiName.'读取商户接收规则失败';
            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$clue_info);
            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        }else{

            foreach ($clue_rule as $v){
                $params[$v['curr']] = $clue_info[$v['orig']];
                if($v['orig'] == 'city'){
                    if (!empty($clue_info['show_city'])) {
                        if (strpos($clue_info['show_city'], '-') !== false) {
                            $city_t = explode('-', $clue_info['show_city']);
                            if (count($city_t) == 3) {
                                $params[$v['curr']] =$city_t[0].'-'.$city_t[1];
                            } elseif (count($city_t) == 2) {
                                $params[$v['curr']] =$city_t[0].'-'.$city_t[1];
                            } elseif (count($city_t) == 1) {
                                $params[$v['curr']] = $city_t[0];
                            }
                        }else{
                            $params[$v['curr']]=$clue_info['show_city'];
                        }
                    }else{
                        $citys = explode('-',$clue_info[$v['orig']]);
                        $city_info = Db::name('city')->where(['type'=>2,'id'=>$citys[1]])->find();
                        $params[$v['curr']] = $city_info['name'];
                    }

                }
            }


            $clue_info['city']= $params['intent_loan_city'];

            $this->getValidate($apiName,$clue_info); // 手机号码的撞库

            if($clue_info['gender']==1){
                $params['gender']='男';
            }elseif ($clue_info['gender']==2){
                $params['gender']='女';
            }else{
                $params['gender']='';
            }

            if(strpos($clue_info['apply_limit'], '-') !== false){
                $moneyArr=explode('-',$clue_info['apply_limit']);
                $moneyNum=count($moneyArr);
                if($moneyNum==1){
                    $MoneyStr=$moneyArr[0];
                }else{
                    $MoneyStr=$moneyArr[1];
                }
            }else{
                $MoneyStr=$clue_info['apply_limit'];
            }
            if(strpos($MoneyStr, '万') !== false){
                preg_match('/\d+/',$MoneyStr,$number);
                if(empty($number[0])){
                    $MoneyStr=0;
                }else{
                    $MoneyStr=$number[0];
                }
                $params['loan_amount']=$MoneyStr*10000;
            }else{
                preg_match('/\d+/',$MoneyStr,$number);
                if(empty($number[0])){
                    $MoneyStr=0;
                }else{
                    $MoneyStr=$number[0];
                }
                $params['loan_amount']=floatval($MoneyStr);
            }


            if($clue_info['pro_id']==3){
                $params['have_house']=true;
            }elseif ($clue_info['pro_id']==4){
                $params['have_car']=true;
            }elseif ($clue_info['pro_id']==5){
                if($clue_info['car']){
                    $params['have_car']=true;
                }
                if($clue_info['house']){
                    $params['have_house']=true;
                }
                if ($clue_info['public_funds']){
                    $params['have_provident_fund']=true;
                }
            }elseif ($clue_info['pro_id']==6){
                $params['have_provident_fund']=true;
            }

//            if(!empty($clue_info['push_channel'])){
//                $source=$clue_info['push_channel'];
//            }else{
//                $advInfo=Db::name('account')->where('adv_id',$clue_info['adv_id'])->find();
//                $source=$advInfo['show_channel'];
//                if(empty($source)){
//                    $source=get_channel_desc($clue_info['type']);
//
//                }
//            }
//            $remarkStr=$source.'-';
//
//            if(empty($clue_info['remark'])){
//            }else{
//                $remark=json_decode($clue_info['remark'],true);
//                if (is_array($remark)){
//                    $remarkArr=[];
//                    $keys=array_keys($remark);
//                    $b=false;//默认索引
//                    //判断关联数组还是索引数组
//                    foreach($keys as $value){
//                        if(!is_int($value)){
//                            $b=true;
//                            break;
//                        }
//                    }
//                    //是关联数组
//                    if($b){
//                        foreach ($remark as $kk=>$vv){
//                            if(strpos($kk, '城市') !== false){
//                            }else{
//                                $remarkArr[]=$vv;
//                            }
//                        }
//                    }else{
//                        foreach ($remark as $vv){
//                            if($clue_info['type']==1){
//                                if(strpos($vv['name'], '城市') !== false){
//                                }else{
//                                    $remarkArr[]=$vv['value'];
//                                }
//                            }else{
//                                if(isset($vv['name'])&&isset($vv['value'])){
//                                    if(strpos($vv['name'], '城市') !== false){
//                                    }else{
//                                        $remarkArr[]=$vv['value'];
//                                    }
//                                }else{
//                                    $remarkArr[]=json_encode($vv,JSON_UNESCAPED_UNICODE);
//                                }
//                            }
//                        }
//                    }
//                }else{
//                    $remarkArr[]=$remark;
//                }
//                $remarkStr=$remarkStr.implode('|',$remarkArr);
//            }
//
//            $params['remark']=$remarkStr;


            $api_url = $mapping['api_url'];

            $postData['param']=$params;

//            dump($params);
//            die;

            $postApi=[
                'data'=>$this->encrypt(json_encode($params,JSON_UNESCAPED_UNICODE)),
            ];

            $postData['data']=$postApi;

//
//            \dump('提交1');
//            \dump($params);
//            \dump($api_url);
//            \dump($postApi);
//            die;
            // 2. 推送线索

            $res_json = $this->postJson($api_url, $postApi);
            $res  = json_decode($res_json, true);
//            dump($res);
//            die;
            if(!empty($res)){
                $res['params'] = $postData;
                if($res['code']!=0){
                    $errMsg=$apiName.'线索推送商户处理失败'.$res['msg'];
                    ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                    model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                    throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
                }else{
                    //看DATA0 是否有数据成功
//                    if(!empty($res['data'][0])){
//                        if(strpos($res['data'][0], '数据成功') === false) {
//                            $errMsg=$apiName.'线索推送商户处理失败';
//                            ClueErrorLog::record($clue_info['clue_id'],'线索推送商户处理失败',$res);
//                            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg.$res['data'][0]]);
//                            throw new ParamException(['msg'=>$errMsg.$res['data'][0],'errorCode'=>10001]);
//                        }
//                    }else{
//                        $errMsg=$apiName.'线索推送商户处理失败';
//                        ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
//                        model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg.$res['msg']]);
//                        throw new ParamException(['msg'=>$errMsg.$res['msg'],'errorCode'=>10001]);
//                    }
                }
            }else{
                $errMsg=$apiName.'线索推送商户请求失败';
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$postData);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
            }

            return $res;
        }
    }


    //1数据推送成功-101非法请求(请检查传值方式是否正确,是否缺少必传参数)-102数据解密失败/或线索构建失败 数据接收已关闭-- 机构方关闭数据接收-103字段映射未配置 -- 机构方未配置字段映射-104未配置加密key -- 机构方未配置加密参数(AES加密key或者iv)-105前置撞库失败 -- 数据接收方已存在该联系方式-106渠道推送数量已达当日上限 拒绝数据推送-107渠道非法 -- 请检查sourceCode 与 accessKey是否正确-108请求过于频繁, 请控制单位时间内的请求次数-200解密失败-- 请检查加解密相关参数及加密方法是否与机构方配置保持一致-300线索推送失败-- 数据推送方请检查代码是否正确, 相关加密是否一致, 推送数据类型是否一致, 字
    //段名与配置是否一致-400线索参数校验失败, 缺少必填参数（姓名，联系电话





    function encrypt($input){
        return base64_encode(openssl_encrypt($input, 'AES-256-CBC', $this->aeskey, OPENSSL_RAW_DATA,$this->aesiv));
    }


    //撞库
    public function getValidate($apiName,$clue_info)
    {
        $phone=$clue_info['phone'];
        $api_url = $this->url.'/api/jqd/clue/repeatCheck';

        $api_params = [
            'city'=>$clue_info['city'],
            'mobile_md5'=>strtolower(md5($phone)),

        ];


        $res_json = $this->postJson($api_url, $api_params);
        $res  = json_decode($res_json, true);

        if(!empty($res)){
            if($res['code']!=200){
                $errMsg=$apiName.'CRM手机号码的撞库失败'.$res['msg'];
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg.$res['code']]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
            }
        }else{
            $errMsg=$apiName.'CRM手机号码的撞库请求失败';
            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$clue_info);
            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        }
        return $res;
    }



    /**
     * post发送json格式的数据
     */
    public function postJson($url, $data)
    {

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            throw new ParamException(['msg'=>'请求数据不能为空','errorCode'=>10000]);
        }
        $data=json_encode($data,JSON_UNESCAPED_UNICODE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json; charset=utf-8',
            'X-Request-Channel:'.$this->app_id,
//            'Content-Type: application/x-www-form-urlencoded' ,

        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

}